<template>
  <XcDrawer ref="drawer" :title="$t('page.app.config')" :width="840" @onDrawerSave="onSave">
    <Form ref="configform" :model="config" :label-width="0" :rules="rules">
      <FormItem prop="name">
        <Input v-model="config.name" maxlength="56" show-word-limit :placeholder="$t('page.app.configform.name')"></Input>
      </FormItem>
    </Form>
    <ConfigSet :properties="config.properties" @onChanged="onChanged" />
  </XcDrawer>
</template>

<script>
  import XcDrawer from '@/components/xcdrawer'
  import ConfigSet from './configset'
  export default {
    name: "comp-configadd",
    components: { XcDrawer, ConfigSet },
    data() {
      return {
        config: {
          name: '',
          properties: '',
        },
        rules: {
          name: [{ required: true, max: 56, pattern: /^[a-z][a-zA-Z0-9_-]{1,55}/, message: this.$t('page.app.configform.namerule'), trigger: 'blur' }],
        },
        proplist: [],
      }
    },
    methods: {
      show(name) {
        this.config.name = name || ''
        this.config.properties = ''
        // ==========================
        this.configs = []
        if (this.config.name !== '') {
          this.$md.dispatch('app_config_list', {
            appname: name
          }).then(data => {
            let configs = data.data || []
            if (configs.length > 0) {
              this.config.properties = configs[0].properties
            }
            this.$refs.drawer.show()
          })
        } else {
          this.$refs.drawer.show()
        }
      },
      onChanged(profile, proplist) {
        this.proplist = proplist
      },
      onSave() {
        this.$refs.configform.validate((valid) => {
          if (valid) {
            let prop
            let propmap = {}
            for (let i in this.proplist) {
              prop = this.proplist[i]
              if (prop.name && /^[a-z][a-zA-Z0-9_-]{1,55}/.test(prop.name)) propmap[prop.name] = prop.value
            }
            this.$md.dispatch('app_config_save', {
              appname: this.config.name,
              dependable: true,
              configs: [{
                properties: JSON.stringify(propmap),
              }],
            }).then(data => {
              if (data.retCode === 1) {
                this.$Message.success(this.$t('submitok'))
                this.$refs.drawer.close(true)
                this.$emit('onRefresh')
              }
            })
          }
        })
      }
    }
  };
</script>
